package com.iotp.controller.admin.index;

import com.alibaba.fastjson.JSONObject;
import com.iotp.controller.admin.base.BaseController;
import com.iotp.entity.base.CodeEnum;
import com.iotp.entity.base.DataMessage;
import com.iotp.entity.menu.Menu;
import com.iotp.entity.organization.Organization;
import com.iotp.entity.role.Role;
import com.iotp.entity.user.CommUser;
import com.iotp.service.menu.MenuService;
import com.iotp.service.organization.OrganizationService;
import com.iotp.service.role.RoleService;
import com.iotp.service.sys.SysService;
import com.iotp.service.userUserRef.UserUserRefService;
import com.iotp.utils.captcha.Captcha;
import com.iotp.utils.captcha.GifCaptcha;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class IndexController extends BaseController {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private SysService sysService;
    @Autowired
    private UserUserRefService userUserRefService;
    @GetMapping("/login")
    public String gotoLoginpage() throws Exception{
        return "admin/index/login";
    }

    /**
     * 系统首页
     * @return
     */
    @GetMapping("/first")
    public String firstPage(){
        return "admin/index/first";
    }

    /**
     * 用户登录
     * @param account 账号
     * @param password 密码
     * @param captcha 验证码
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/executeLogin")
    public DataMessage executeLogin(
            @RequestParam(required = true, value = "account") String account,
            @RequestParam(required = true, value = "password") String password,
            @RequestParam(required = true, value = "captcha") String captcha) throws Exception {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        if(request.getSession().getAttribute("captcha") != null && request.getSession().getAttribute("captcha").toString().equalsIgnoreCase(captcha)) {
            dm = this.sysService.Login(account, password);
            if(dm.getResult() == 0){
                Map<String, Object> map = (Map<String, Object>) dm.getData();
                setSession(CodeEnum.当前用户.msg, map.get("cur_user"));
                Organization org = (Organization) map.get("cur_org");
                setSession(CodeEnum.当前用户机构.msg, org);
            }
        }else{
            dm.setResult(CodeEnum.失败.code);
            dm.setData(null);
            dm.setMessage("验证码不正确");
        }
        return dm;
    }

    @GetMapping("/session")
    public String session() throws Exception{
        return "admin/index/session";
    }

    /**
     * 进入主页
     * @return
     * @throws Exception
     */
    @GetMapping("/main")
    public String gotoMainPage() throws Exception{
        CommUser user = getCurUser();

        // 获取登录用户信息

        // 查询用户机构信息
        List<Organization> orgList = this.organizationService.queryUserOrgs(user.getNewuserId());
        Organization org = orgList.get(0);

        super.setOrgId(org.getOrgId());
        super.setOrgCode(org.getOrgCode());
        super.setOrgType(org.getOrgType());

        // 查询用户角色信息
        List<Role> userRoles = this.roleService.queryRoleByUserId(user.getNewuserId());
        Set<Menu> menuSet = new HashSet<Menu>();
        ArrayList<Menu> menus = new ArrayList<Menu>();

        for(Role role : userRoles) {
            List<Menu> menuList = this.menuService.queryMenuByRoleId(role.getRoleId());
            for(Menu menu: menuList) {
                menuSet.add(menu);
            }
        }
        // 构建菜单List
        for(Menu menu : menuSet) {
            menus.add(menu);
        }
        // 菜单排序
        Comparator<Menu> comparator = new Comparator<Menu>() {
            public int compare(Menu m1, Menu m2) {
                Integer m1Order = m1.getMenuOrder();
                Integer m2Order = m2.getMenuOrder();
                if(m1Order != null && m2Order != null) {
                    // 自定义排序
                    if (m1.getMenuOrder().intValue() != m2.getMenuOrder().intValue()) {
                        return m1.getMenuOrder().intValue() - m2.getMenuOrder().intValue();
                    } else {
                        // menuId排序
                        return Integer.parseInt(String.valueOf(m1.getMenuId().longValue() - m2.getMenuId().longValue()));
                    }
                } else {
                    return Integer.parseInt(String.valueOf(m1.getMenuId().longValue() - m2.getMenuId().longValue()));
                }
            }
        };
        Collections.sort(menus, comparator);
        request.getSession().setAttribute("menus", menus);
        request.setAttribute("menus", menus);
        request.setAttribute("username", user.getUserNameCn());
        return "admin/main/main";
    }
    /**
     * 获取验证码
     */
    @GetMapping("/captcha")
    @ResponseBody
    public void executeCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/gif");
        Captcha captcha = new GifCaptcha(100,40,4);
        HttpSession session = request.getSession(true);
//	        Captcha captcha = new SpecCaptcha(146,33,4);
        //输出
        captcha.out(response.getOutputStream());
        //存入Session
        session.setAttribute("captcha",captcha.text().toLowerCase());
    }

    /**
     * 退出登录
     * @return index/login
     */
    @GetMapping("/logout")
    public String executeLogout() throws Exception {
        request.getSession().removeAttribute(CodeEnum.当前用户机构.msg);
        request.getSession().removeAttribute(CodeEnum.当前用户.msg);
        return "redirect:login";
    }

}

